#!/usr/bin/env python
# encoding: utf-8


from app.views.api import route_api
from  flask import request,jsonify
import json

from sqlalchemy import desc, func, or_

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicOutLog
from app.model import ElectronicOutOrder
from app.model import ElectronicOutOrderItem

from app.common.libs.Logging import logger
from app.common.libs.Helper import getCurrentDate, getFormatDate
from app.common.libs.UserService import UserService

from app.common.libs.electronic.OutOrderService import OutOrderService
from app.common.libs.electronic.OutCartService import OutCartService

@route_api.route("/electronic/out/order/create",methods = [ "GET","POST" ])
def outOrderCreate():
    resp = { 'code':20000,'message':'出库订单创建成功~', 'data':{}}
    req = request.values
    electronics = req['electronics'] if 'electronics' in req else None
    items = []
    if electronics:
        items = json.loads(electronics)

    if len( items ) < 1:
        resp['code'] = -1
        resp['message'] = "下单失败：未选择元器件~~"
        return jsonify(resp)

    user_info = UserService.getUserInfo(request)
    if not user_info :
        resp['code'] = -1
        resp['message'] = "下单失败：用户未登录~~"
        return jsonify(resp)

    target=OutOrderService()
    note = req['note'] if 'note' in req else ''
    params={
        'note': note,
        'price':'100',
        'price_sum':'1000'
        }
    # 创建订单
    resp=target.createOrder( user_info.id, items, params)

	# 下单成功将下单的元器件去掉
    if resp['code'] == 20000:
        OutCartService.deleteItem( user_info.id, items )

    return jsonify( resp )

@route_api.route("/electronic/out/order/list",methods = [ "GET","POST" ])
def outOrderList():
    resp = { 'code':20000,'message':'出库订单查询成功~', 'data':{}}

    req = request.values
    keywords = req['keywords'] if 'keywords' in req else ''
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    datetimeStart = req['datetimeStart'][:19].replace('T',' ') if 'datetimeStart' in req else ''
    datetimeEnd = req['datetimeEnd'][:19].replace('T',' ') if 'datetimeEnd' in req else ''
    # 分页偏移量
    offset = ( page - 1 ) * limit

    if datetimeStart and not datetimeEnd:
        datetimeEnd = '3000-01-01 00:00:00'
    if datetimeEnd and not datetimeStart:
        datetimeStart = '1970-01-01 00:00:00'
    if not datetimeEnd and not datetimeStart:
        datetimeStart = '1970-01-01 00:00:00'
        datetimeEnd = '3000-01-01 00:00:00'

    user_info = UserService.getUserInfo(request)
    roles = user_info.roles.split(';')

    total = 0
    rule = func.concat(User.nickname, ElectronicOutOrder.order_sn, ElectronicOutOrder.note).op('regexp')('.*%s.*'%keywords.replace(' ','.*'))
    #  rule = or_(ElectronicOutOrder.order_sn.ilike("%{0}%".format(keywords)), ElectronicOutOrder.note.ilike("%{0}%".format(keywords)))
    query = db.session.query(User.nickname,
                            ElectronicOutOrder.order_sn,
                            ElectronicOutOrder.status,
                            ElectronicOutOrder.created_time,
                            ElectronicOutOrder.note
                            )\
                            .filter( ElectronicOutOrder.user_id == User.id )\
                            .filter( ElectronicOutOrder.created_time >= datetimeStart )\
                            .filter( ElectronicOutOrder.created_time <= datetimeEnd )\
                            .filter( rule )

    if not "库管" in roles:
        query = query.filter( User.id == user_info.id )

    total = query.count()
    order_list = query.order_by(desc(ElectronicOutOrder.created_time)).offset( offset ).limit( limit ).all()

    data = []
    for item in order_list:
        status = ''
        if item[2]==0:
            status = '订单无效'
        elif item[2]==1:
            status = '待出库'
        elif item[2]==2:
            status = '已出库'
        data.append({
            'user': item[0],
            'sn': item[1],
            'status': status,
            'created_time': getFormatDate(item[3]),
            'note': item[4],
        })
    resp['data']['items'] = data
    resp['data']['total'] = total

    return jsonify( resp )


@route_api.route("/electronic/out/order/info",methods = [ "GET","POST" ])
def outOrderInfo():
    resp = { 'code':20000,'message':'出库订单查询成功~', 'data':{}}
    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    user_info = UserService.getUserInfo(request)

    order_item_list = db.session.query(
                                    Electronic.name,
                                    Electronic.sn,
                                    Electronic.position,
                                    ElectronicOutOrderItem.count,
                                    ElectronicOutOrderItem.status,
                                    ElectronicOutOrderItem.note)\
                                    .filter( ElectronicOutOrderItem.electronic_out_order_id == ElectronicOutOrder.id )\
                                    .filter( ElectronicOutOrderItem.electronic_id == Electronic.id )\
                                    .filter( ElectronicOutOrder.order_sn == sn )\
                                    .all()
    data = []
    for item in order_item_list:
        status = ''
        if item[4]==0:
            status = '成功'
        elif item[4]==1:
            status = '失败'
        data.append({
            'electronic_name': item[0],
            'electronic_sn': item[1],
            'electronic_position': item[2],
            'count': item[3],
            'status': status,
            'note': item[5],
            })
    resp['data'] = data

    return jsonify( resp )

@route_api.route("/electronic/out/order/delete",methods = [ "GET","POST" ])
def outOrderDelete():
    resp = { 'code':20000,'message':'出库订单删除成功~', 'data':{}}
    return jsonify( resp )

@route_api.route("/electronic/out/order/outstock",methods = [ "GET","POST" ])
def outOrderOutStock():
    resp = { 'code':20000,'message':'元器件出库成功~', 'data':{}}
    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    order_info = db.session.query(ElectronicOutOrder).filter_by(order_sn = sn).first()
    if order_info.status == 2:
        resp['code'] = -1
        resp['message'] = "出库失败，当前订单已经出库，无需重复出库~~"
        return jsonify(resp)

    order_item_list = db.session.query(ElectronicOutOrderItem)\
                                    .filter( ElectronicOutOrderItem.electronic_out_order_id == ElectronicOutOrder.id )\
                                    .filter( ElectronicOutOrder.order_sn == sn )\
                                    .all()
    user_info = UserService.getUserInfo(request)
    for item in order_item_list:
        out_stock_model = ElectronicOutLog()
        out_stock_model.user_id = user_info.id
        out_stock_model.electronic_id = item.electronic_id
        out_stock_model.count = item.count
        out_stock_model.note = item.note
        out_stock_model.created_time = getCurrentDate()
        db.session.add(out_stock_model)

    # 更新订单中出库时间
    order_info.status = 2
    order_info.out_time = out_stock_model.created_time
    db.session.commit()

    return jsonify( resp )







